package com.lora.service.resolver;

import com.google.common.base.Strings;
import com.lora.dto.EquipmentDto;
import com.lora.entity.Wirelesssmokefeel;
import com.lora.enums.WirelessSmokeFeelEnum;
import com.lora.service.NodeDataResolver;
import com.lora.service.WirelesssmokefeelService;
import org.springframework.stereotype.Service;
import org.springframework.util.Base64Utils;

import javax.annotation.Resource;
import java.math.BigDecimal;

/**
 * 无线烟感数据节点上报数据解析器
 */
@Service("smokeSensorsNodeDataResolver")
public class WirelessSmokeFeelResolver implements NodeDataResolver<Wirelesssmokefeel> {

    @Resource
    private WirelesssmokefeelService wirelesssmokefeelService;

    /**
     * @param equipmentNumber
     * @param data
     * @return
     *
     *     终端设备状态事件定义(JTY - GD - H605烟感), 占用3个字节，第三个字节为电量值(电压计算公式 0.038*AD(根据平台值转换为十进制)+0.9)：
     *     1）火警（01H）020100
     *     2）传感器故障（02H）020200
     *     3）电池低电压（03H）020300
     *     4）火警消除（04H）020400
     *     5）传感器故障消除(05H) 020500
     *     6）低电压恢复(06H) 020600
     *     7）正常状态(00H) 020000
     *     8）探测器上电（0EH）020E00
     *     9）按键自检（0DH）；020D00
     *
     *     示例：烟感上报的状态数据AgDY，解码并转换成16进制。转换后的三个字节分别是 02 00 D8 ，
     *     前两个字节02 00对应协议 7)正常状态，第三个字节D8为电量值转为10进制是218，
     *     根据电压计算公式 0.038*218+0.9=9.18，即电池电压为9.18V。
     *
     */
    @Override
    public EquipmentDto<Wirelesssmokefeel> resolve(String equipmentNumber, String data) {
        EquipmentDto<Wirelesssmokefeel> equipmentData = new EquipmentDto();
        Wirelesssmokefeel wirelesssmokefeel = new Wirelesssmokefeel();
        // 解析设备状态
        byte[] sources = Base64Utils.decodeFromString(data);
        String b1ToHex = Integer.toHexString(sources[0] & 0xff);
        b1ToHex = Strings.padStart(b1ToHex, 2, '0');
        String b2ToHex = Integer.toHexString(sources[1] & 0xff);
        b2ToHex = Strings.padStart(b2ToHex, 2, '0');
        String code = Strings.padEnd(b1ToHex + b2ToHex, 6, '0');
        WirelessSmokeFeelEnum statusByPre2bit = WirelessSmokeFeelEnum.getStatusByPre2bit(code);
        // 解析设备电压
        String b3ToHex = Integer.toHexString(sources[2] & 0xff);
        b3ToHex = Strings.padStart(b3ToHex, 2, '0');
        int source = Integer.parseInt(b3ToHex.toUpperCase(), 16);
        BigDecimal voltage = new BigDecimal("0.038").multiply(new BigDecimal(source + "")).add(new BigDecimal("0.09"));
        wirelesssmokefeel.setEquipmentid(equipmentNumber);
        wirelesssmokefeel.setDatastring(data);
        wirelesssmokefeel.setState(statusByPre2bit.getReserve());
        wirelesssmokefeel.setVoltage(voltage);
        equipmentData.setEntity(wirelesssmokefeel);
        return equipmentData;
    }

    @Override
    public Wirelesssmokefeel save(Wirelesssmokefeel equipment, boolean alarmFlag) {
        equipment.setAlarmFlag(alarmFlag);
        wirelesssmokefeelService.save(equipment);
        return equipment;
    }

}
